<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ include file="/WEB-INF/t/hplus/include/taglib.jsp"%>

<!DOCTYPE html>
<html>

<head>
    <title>商户管理</title>
	<%@ include file="/WEB-INF/t/hplus/include/head.jsp"%>
	
	<link href="${ctxStatic}/css/plugins/select2/select2.min.css" rel="stylesheet">
	<style type="text/css">
	 .select2-dropdown{z-index: 3051 !important;/*99*/}
	</style>	
</head>

<body>
    <div class="wrapper wrapper-content animated fadeInRight">
   	   <div class="row"> 
	    <div class="col-sm-12"> 
	     <div class="float-e-margins"> 
	      <div class="no-padding"> 
			<div id="merchantToolbar" class="btn-group hidden-xs" role="group"> 
			 <button type="button" class="addMerchant btn btn-outline btn-default" title="添加商户"> <i class="glyphicon glyphicon-plus" aria-hidden="true"></i> 添加</button> 
			</div>
			<table id="merchantList"></table>
	      </div> 
	     </div> 
	    </div> 
	   </div> 
    </div>
    
<div id="merchantModal" class="modal fade" aria-hidden="true">
	<div class="modal-dialog">
		<div class="modal-content animated bounceInUp">
	       <form class="form-horizontal" id="merchantForm">
			<div class="modal-header">
				<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span></button>
				<h4 class="modal-title"></h4>
			</div>
			<div class="modal-body">
		        <input type="hidden" id="id" name="id">
		        <div class="form-group"> 
		         <label class="col-sm-3 control-label">商户名称：</label> 
		         <div class="col-sm-8"> 
		          <input id="name" name="name" class="form-control" type="text"> 
		         </div> 
		        </div> 
		        <div class="form-group"> 
		         <label class="col-sm-3 control-label">商户行业：</label> 
		         <div class="col-sm-8"> 
		          <select id="industryType" name="industryType" class="form-control m-b"></select>
		         </div> 
		        </div>
		        <div class="form-group"> 
		         <label class="col-sm-3 control-label">所属地区：</label> 
		         <div class="col-sm-8"> 
                      <select id="regionId" name="regionId" class="js-states form-control" style="width: 100%"></select>
		         </div> 
		        </div> 		        
		        <div class="form-group"> 
		         <label class="col-sm-3 control-label">是否启用：</label> 
		         <div class="col-sm-8"> 
                     <div class="radio i-checks">
                         <input type="radio" value="1" name="isEnabled" checked="checked"> <i></i> 是
                         <input type="radio" value="0" name="isEnabled"> <i></i> 否
                     </div>
		         </div> 
		        </div>
		        <div class="form-group"> 
		         <label class="col-sm-3 control-label">商户简介：</label> 
		         <div class="col-sm-8"> 
		          <input id="description" name="description" class="form-control" type="text">
		         </div> 
		        </div>
		        <input type="hidden" id="managerId" name="managerId">
		        <div class="form-group"> 
		         <label class="col-sm-3 control-label">管理员登录名称：</label> 
		         <div class="col-sm-8"> 
		          <input id="managerLoginName" name="managerLoginName" class="form-control" type="text"> 
		         </div> 
		        </div> 
		        <div class="form-group"> 
		         <label class="col-sm-3 control-label">管理员真实姓名：</label> 
		         <div class="col-sm-8"> 
		          <input id="managerRealName" name="managerRealName" class="form-control" type="text"> 
		         </div> 
		        </div>
			</div>
			<div class="modal-footer">
		          <button class="btn btn-primary" type="submit">提交</button> 
		          <button class="btn btn-white" type="submit" data-dismiss="modal">关闭</button>
			</div>
			</form> 
		</div>
	</div>
</div>

<div class="modal fade" id="openIdModal" role="dialog" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content animated bounceInUp">
        <form class="form-horizontal" id="bindForm">
        	<input type="hidden" id="mid" name="mid">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title">绑定微信</h4>
            </div>
            <div class="modal-body">
		        <div class="form-group"> 
		         <label class="col-sm-3 control-label">URL：</label> 
		         <div class="col-sm-8"> 
		          <input id="serverUrl" name="serverUrl" class="form-control" type="text"> 
		         </div> 
		        </div> 
		        <div class="form-group"> 
		         <label class="col-sm-3 control-label">TOKEN：</label> 
		         <div class="col-sm-8"> 
		          <input id="serverToken" name="serverToken" class="form-control" type="text"> 
		         </div> 
		        </div> 
		        <div class="form-group"> 
		         <label class="col-sm-3 control-label">AppId：</label> 
		         <div class="col-sm-8"> 
		          <input id="appId" name="appId" class="form-control" type="text"> 
		         </div> 
		        </div> 
		        <div class="form-group"> 
		         <label class="col-sm-3 control-label">AppSecret：</label> 
		         <div class="col-sm-8"> 
		          <input id="appSecret" name="appSecret" class="form-control" type="text"> 
		         </div> 
		        </div> 	
		        <div class="form-group"> 
		         <label class="col-sm-3 control-label">AccountId：</label> 
		         <div class="col-sm-8"> 
		          <input id="accountId" name="accountId" class="form-control" type="text"> 
		         </div> 
		        </div> 	
		        <div class="form-group"> 
		         <label class="col-sm-3 control-label">ValidCode：</label> 
		         <div class="col-sm-8"> 
		          <input id="valid_code" name="valid_code" class="form-control" type="text"> 
		         </div> 
		        </div> 	
		        <div class="form-group"> 
		         <label class="col-sm-3 control-label">EncodingAESKey：</label> 
		         <div class="col-sm-8"> 
		          <input id="encodingAESKey" name="encodingAESKey" class="form-control" type="text"> 
		         </div> 
		        </div> 	
		        <div class="form-group"> 
		         <label class="col-sm-3 control-label">ApiKey：</label> 
		         <div class="col-sm-8"> 
		          <input id="apiKey" name="apiKey" class="form-control" type="text"> 
		         </div> 
		        </div> 	
		        <div class="form-group"> 
		         <label class="col-sm-3 control-label">NotifyUrl：</label> 
		         <div class="col-sm-8"> 
		          <input id="notifyUrl" name="notifyUrl" class="form-control" type="text"> 
		         </div> 
		        </div> 	
		        <div class="form-group"> 
		         <label class="col-sm-3 control-label">UniUrl：</label> 
		         <div class="col-sm-8"> 
		          <input id="uniUrl" name="uniUrl" class="form-control" type="text"> 
		         </div> 
		        </div> 	
		        <div class="form-group"> 
		         <label class="col-sm-3 control-label">MchId：</label> 
		         <div class="col-sm-8"> 
		          <input id="mchId" name="mchId" class="form-control" type="text"> 
		         </div> 
		        </div> 	
            </div>
            <div class="modal-footer">
		          <button class="btn btn-primary" type="submit">提交</button> 
		          <button class="btn btn-white" type="submit" data-dismiss="modal">关闭</button>
            </div>
        	</form>
        </div>
    </div>
</div>

<div class="modal fade" id="delModal" role="dialog" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content animated bounceInUp">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title">删除商户</h4>
            </div>
            <div class="modal-body">
                <p>确定删除该商户吗？</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-white" data-dismiss="modal">放弃</button>
                <button type="button" class="btn btn-primary" id="delOk">确定</button>
            </div>
        </div>
    </div>
</div>

<script src="${ctxStatic}/js/plugins/select2/select2.full.min.js"></script>
<script src="${ctxStatic}/js/plugins/select2/i18n/zh-CN.js"></script>

<script type="text/javascript">
	$.fn.modal.Constructor.prototype.enforceFocus = function() {};
	var $table = $("#merchantList"),
		$s2Region,
		$delModal = $('#delModal');
	
	$(document).ready(function(){
		$table.bootstrapTable({
			url: "${ctx}/pmerchant/list", //get请求, 如果cache为false默认会加随机数, 如果列排序sortable=true则还会加sort和order
			cache: false,
			pagination: true,
	        sidePagination: 'server', // client or server
	        dataField: 'list',
	        pageNumber: 1,
	        pageSize: 10,
	        pageList: [10, 25, 50, 100],
			showRefresh: true,
			showToggle: true,
			showColumns: true,
	        toolbar: '#merchantToolbar',
	        iconSize : "outline",
	        rowStyle: function(row, index){
	        	if(row.isEnabled == 0){
					return {
		            	classes: 'danger'
		        	};
	        	}else{
	        		return {}
	        	}
	        },
	        columns:[{
	        	field:'name',
	        	title:'商户名称',
	        	width: 250,
	        	align:'center'
	        },{
	        	field:'industryType',
	        	title:'商户行业',
	        	align:'center'
	        },{
	        	field:'createTime',
	        	title:'创建时间',
	        	align:'center'
	        },{
	        	field:'isEnabled',
	        	title:'是否启用',
	        	width: 100,
	        	align:'center',
	        	formatter: function(value, row, index){
					switch(value){
						case 0 :
							return '停用';
							break;
						case 1 :
							return '正常';
							break;
					}
				}
	        },{
	        	field:'description',
	        	title:'描述',
	        	align:'center'
	        },{
	        	field:'action',
	        	title:'操作',
	        	align:'center',
	        	formatter: function(value, row, index){
					var str = '&nbsp;';
					str += '<a href="javascript:void(0)" onclick="editMerchant('+ row.id +');" >编辑</a>';
					str += '&nbsp;|&nbsp;';
					str += '<a href="javascript:void(0)" onclick="bindOpenId('+ row.id +');" >绑定微信</a>';
					str += '&nbsp;|&nbsp;';
					str += '<a href="${ctx}/pwmenu">公众号菜单</a>';
					str += '&nbsp;|&nbsp;';
					//str += '<a href="javascript:void(0)" onclick="bindMerchantToWxModal('+ row.id +');" >配置授权</a>';
					//str += '&nbsp;|&nbsp;';
					str += '<a href="javascript:void(0)" onclick="showDelModal('+ row.id +');" >删除</a>';
					str += '&nbsp;';
					return str;
				}
	        }]
		});
		
		$('.addMerchant').click(function () {
			showModal("添加商户");
	    });
		
		//提示信息样式
		toastr.options = {
			closeButton: true,
			progressBar: true,
			positionClass: "toast-top-right", //toast-top-center, toast-top-right
			onclick: null,
			timeOut: 2000
		};
		
	});
	
	function editMerchant(id){
		$.ajax({
			type: "GET",
			async: false,
			data: {"id": id, "r": Math.random()},
			dataType: "json",
			url: "${ctx}/pmerchant/get",
			success: function(data){
				showModal("编辑商户", data);
			},
			error: function(){
				toastr.error("查询商户失败！");
			}
		});
	}
	
	function bindOpenId(id){
		$.ajax({
			type: "GET",
			async: false,
			data: {"id": id, "r": Math.random()},
			dataType: "json",
			url: "${ctx}/pmerchant/get",
			success: function(data){
				showBindOpenIdModal("绑定微信", data);
			},
			error: function(){
				toastr.error("查询商户失败！");
			}
		});
	}
	function showBindOpenIdModal(title, row) {
		$('#openIdModal').off();
		
		var $modal = $('#openIdModal').modal({
			"backdrop": 'static', //禁止模态失去焦点关闭
			"show": true
		});
		$modal.find('.modal-title').text(title);
		
		$('#openIdModal').on("shown.bs.modal", function(){
			$("#serverUrl").focus();
		});
		$('#openIdModal').on("hidden.bs.modal", function(){
			//重置表单
			$("#bindForm")[0].reset();
			$("#mid").val("");
		});

		//表单赋值
		if(row){
			for (var name in row) {
				switch(name){
					case "id" :
						$modal.find('input[name=mid]').val(row[name]);
						break;
					default:
						$modal.find('input[name=' + name + ']').val(row[name]);
				}
			}
		}
		
		//表单校验及提交
		var e = "<i class='fa fa-times-circle'></i> ";
		$("#bindForm").validate({
			rules : {
				serverUrl : {
					required : !0,
					minlength : 1,
					maxlength : 200
				},
				serverToken : {
					required : !0,
					minlength : 1,
					maxlength : 200
				},
				appId : {
					required : !0,
					minlength : 1,
					maxlength : 200
				},
				appSecret : {
					required : !0,
					minlength : 1,
					maxlength : 200
				}
			},
			messages : {
				serverUrl : {
					required : e + "请输入serverUrl",
					minlength : e + "serverUrl必须1字符以上",
					maxlength : e + "serverUrl最多200个字符"
				},
				serverToken : {
					required : e + "请输入serverToken",
					minlength : e + "serverToken必须1字符以上",
					maxlength : e + "serverToken最多200个字符"
				},
				appId : {
					required : e + "请输入appId",
					minlength : e + "appId必须1字符以上",
					maxlength : e + "appId最多200个字符"
				},
				appSecret : {
					required : e + "请输入appSecret",
					minlength : e + "appSecret必须1字符以上",
					maxlength : e + "appSecret最多200个字符"
				}
			},
			submitHandler: function(form){
				$(form).ajaxSubmit({
					type: "POST",
					dataType: "json",
					url: "${ctx}/pmerchant/bindOpenId",
					success: function(data){
						if(data.success){
							$modal.modal("hide");
							$table.bootstrapTable("refresh");
							toastr.success(data.msg);
						}else{
							toastr.error(data.msg);
						}
					},
					error: function(data){
						toastr.error("绑定微信失败！");
					}
				});
			}
		});
	}
	
	function showDelModal(id){
		$delModal = $('#delModal').modal({
			"backdrop": 'static',
			"show": true
		});
		
		$('#delOk').off();
		$('#delOk').on('click', function(){
			deleteMerchant(id);
		});
		
		$delModal.modal('show');
	}
	
	function deleteMerchant(id){
		$.ajax({
			type: "POST",
			async: false,
			data: {"id": id},
			dataType: "json",
			url: "${ctx}/pmerchant/delete",
			success: function(data){
				if(data.success){
					$delModal.modal("hide");
					$table.bootstrapTable("refresh");
					toastr.success(data.msg);
				}else{
					$delModal.modal("hide");
					toastr.error(data.msg);
				}
			},
			error: function(){
				$delModal.modal("hide");
				toastr.error("删除商户失败！");
			}
		});
	}
	
	function showModal(title, row) {
		$('#merchantModal').off();
		
		var $modal = $('#merchantModal').modal({
			"backdrop": 'static', //禁止模态失去焦点关闭
			"show": true
		});
		$modal.find('.modal-title').text(title);
		
		//iCheck
		$(".i-checks").iCheck({
			checkboxClass:"icheckbox_square-green",
			radioClass:"iradio_square-green"
		});
		
		$('#merchantModal').on("shown.bs.modal", function(){
			$("#name").focus();
			initIndustryType(row);
			initSelect2Region(row);
		});
		$('#merchantModal').on("hidden.bs.modal", function(){
			//重置表单
			$("#merchantForm")[0].reset();
			$("#id").val("");
			$s2Region.select2("destroy");
			$modal.find('input:radio[name=isEnabled][value=1]').iCheck('check');
		});

		//表单赋值
		if(row){
			for (var name in row) {
				switch(name){
					case "industryType" :
						$("#industryType").val(row[name]);
						break;
					case "isEnabled" :
						$modal.find('input:radio[name='+name+'][value='+row[name]+']').iCheck('check');
						break;							
					/**case "businessUser" :
						$modal.find('input[id=loginName]').val(row[name]?row[name].loginName:"");
						$modal.find('input[id=realName]').val(row[name]?row[name].realName:"");
						break;*/						
					default:
						$modal.find('input[name=' + name + ']').val(row[name]);
				}
			}
		}
		
		//表单校验及提交
		var e = "<i class='fa fa-times-circle'></i> ";
		$("#merchantForm").validate({
			rules : {
				name : {
					required : !0,
					minlength : 1,
					maxlength : 50
				},
				managerLoginName : {
					required : !0,
					minlength : 1,
					maxlength : 20
				}
			},
			messages : {
				name : {
					required : e + "请输入商户名称",
					minlength : e + "商户名称必须1字符以上",
					maxlength : e + "商户名称最多50个字符"
				},
				managerLoginName : {
					required : e + "请输入商户管理员登录名称",
					minlength : e + "商户管理员登录名称必须1字符以上",
					maxlength : e + "商户管理员登录名称最多20个字符"
				}
			},
			submitHandler: function(form){
				$(form).ajaxSubmit({
					type: "POST",
					dataType: "json",
					url: "${ctx}/pmerchant/save",
					success: function(data){
						if(data.success){
							$modal.modal("hide");
							$table.bootstrapTable("refresh");
							toastr.success(data.msg);
						}else{
							toastr.error(data.msg);
						}
					},
					error: function(data){
						toastr.error("保存商户失败！");
					}
				});
			}
		});
	}
	
	function initIndustryType(row){
		//取上级商户行业类型并填充下拉
		$.ajax({
			type: "GET",
			async: false,
			data: {type:"industry_type"},
			dataType: "json",
			url: "${ctx}/pdict/list",
			success: function(data){
				var options = "";
				$.each(data, function(i,item){
					options = options + "<option value='"+item.id+"'>"+item.label+"</option>";
				});
				$("#industryType").html(options);
			},
			error: function(data){
				toastr.error("查询商户行业失败！");
				$modal.modal("hide");
			}
		});
		if(row){
			$("#industryType").val(row["industryType"]);
		}
	}
	
	function initSelect2Region(row){
		var node = {"id" : 0, "name" : "请选择所属地区"};
		if(row && row["regionId"] && row["regionId"] != 0){
			node.id = row["regionId"];
			node.name = row["regionName"];
		}
		$("#regionId").html('<option value="'+node.id+'" selected="selected">'+node.name+'</option>');
		//$s2Parent.val(node.id).trigger("change");
		$s2Region = $("#regionId").select2({
			id: "sssss2Region",
			language: "zh-CN",
			/*placeholder: {
				id: node.id,
				name: node.name
			} ,*/
			//allowClear:true,
			//theme: "bootstrap",
			ajax: {
				type: "GET",
				async: false,
				dataType: "json",
				url: "${ctx}/region/list",
				delay: 500,
				data: function(params){
					params.page = params.page || 1;
					var query = {
						name: params.term, // ? encodeURI(encodeURI(params.term)) : ""
						limit: 10,
						offset: (params.page-1)*10
					}
					return query;
				},
				processResults: function (data, params) {
					params.page = params.page || 1;
			        return {
			        	results: data.list,
			        	pagination: {
			                more: params.page < data.totalPages
			            }
			        };
				},
				cache: false,
				error: function(data){
					toastr.error("查询地区失败！");
					$modal.modal("hide");
				}
			},
			escapeMarkup: function (markup) {
				return markup;   
			},
			minimumInputLength: 1,
			templateResult: function(repo){
				if (repo.loading) return repo.text;
				return repo.name;
				/*if(repo.name){
					var markup = '<div class="clearfix">' +  
					'<div class="col-sm-2">' + repo.id + '</div>' +  
					'<div class="col-sm-8">' + repo.name + '</div>' +  
					'</div>';  
					 return markup;
				}*/
			},  
			templateSelection: function(repo){
				return repo.name || repo.text;
			}
		});
	}
	
</script>

</body>
</html>